<template>
  <el-col>
    <div ref="info" class="bar-chart"></div>
  </el-col>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue'
import { useMapDataStore } from '@/stores/statistics/mapData.js'
import { useGridStore } from '@/stores/grid/grid.js'
import { useAqiFeedbackStore } from '@/stores/aqi/aqiFeedback.js'

const gridStore = useGridStore()
const aqiFeedbackStore = useAqiFeedbackStore()
const mapDataStore = useMapDataStore()
const { proxy } = getCurrentInstance() //获取Vue3全局配置
const info = ref() //用来获取对应标签组件

// console.log(mapDataStore.topTenByCount)

onMounted(async () => {
  if (mapDataStore.mapData === null || mapDataStore.mapData.length === 0) {
    if (gridStore.grids.length === 0) {
      await gridStore.loadData()
    }
    const names = gridStore.grids.map((item) => item.gname)
    mapDataStore.mapData = await aqiFeedbackStore.getData(names)
  }

  const infoEl = info.value //获取ref="info"的标签组件
  const userEc = proxy.$echarts.init(infoEl, 'light') //proxy.$echarts是在获取全局配置中的echarts，这样就不需要在每个vue中import echarts了
  const option = {
    title: {
      text: '各省AQI上报情况（前十）',
      left: '20%', // 水平居中
      textStyle: {
        color: '#fff',
        fontSize: 17,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    // 调整图表布局
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '20%',
      containLabel: true
    },
    // 调整x轴和y轴的样式
    xAxis: [
      {
        type: 'category',
        data: mapDataStore.topTenByCount.map((item) => item.name),
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          interval: 0,
          rotate: 45,
          margin: 20
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#ccc'
          }
        }
      }
    ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '90%',
        data: mapDataStore.topTenByCount.map((item) => item.value),
        itemStyle: {
          color: function (params) {
            // 使用一个颜色数组，为每个柱子分配不同的颜色
            var colorList = [
              '#5793f3',
              '#d14a61',
              '#675bba',
              '#5ab1ef',
              '#fdbf74',
              '#ffdb5c',
              '#2ec7c9',
              '#b6a29a',
              '#8b4858',
              '#3a8ee6'
            ]
            return colorList[params.dataIndex]
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        },
        animationDuration: 1000,
        emphasis: {
          itemStyle: {
            color: '#fa8c16'
          }
        }
      }
    ]
  }
  userEc.setOption(option) //将图标挂载到标签组件
})
</script>

<style scoped lang="scss">
.bar-chart {
  width: 300px;
  height: 300px;
  padding-top: 20px;
}
</style>
